package com.outdoor.server.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.outdoor.common.constant.MessageConstant;
import com.outdoor.common.constant.StatusConstant;
import com.outdoor.common.exception.AccountLockedException;
import com.outdoor.common.exception.AccountNotFoundException;
import com.outdoor.common.exception.PasswordErrorException;
import com.outdoor.common.result.PageResult;
import com.outdoor.pojo.dto.AdminDTO;
import com.outdoor.pojo.dto.AdminLoginDTO;
import com.outdoor.pojo.dto.AdminPageQueryDTO;
import com.outdoor.pojo.entity.Admin;
import com.outdoor.pojo.entity.Region;
import com.outdoor.pojo.vo.AdminVO;
import com.outdoor.server.mapper.AdminMapper;
import com.outdoor.server.mapper.RegionMapper;
import com.outdoor.server.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RegionMapper regionMapper;
    /**
     * 登录
     * @param adminLoginDTO
     * @return
     */
    public Admin login(AdminLoginDTO adminLoginDTO) {
        String password = adminLoginDTO.getPassword();
        String username = adminLoginDTO.getUsername();
        Admin admin = adminMapper.selectByUsername(username);
        //处理异常情况
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_PASSWORD_ERROR);
        }
        //密码校验
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!password.equals(admin.getPassword())){
            throw new PasswordErrorException(MessageConstant.ACCOUNT_PASSWORD_ERROR);
        }
        //账号锁定
        if(admin.getStatus() == StatusConstant.DISABLE){
            //账号被锁定
            throw  new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        return admin;
    }

    /**
     * 新增管理员
     * @param adminDTO
     */
    public void add(AdminDTO adminDTO) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDTO, admin);
        //默认密码
        admin.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置类型默认为区域管理员
        admin.setType(Admin.REGION_ADMIN);
        //设置账号为启用状态
        admin.setStatus(StatusConstant.ENABLE);
        admin.setCreatedTime(LocalDateTime.now());
        adminMapper.insert(admin);
    }


    /**
     * 分页查询
     * @param adminPageQueryDTO
     * @return
     */
    public PageResult page(AdminPageQueryDTO adminPageQueryDTO) {
        PageHelper.startPage(adminPageQueryDTO.getPage(), adminPageQueryDTO.getPageSize());
        Page<Admin> page = adminMapper.pageQuery(adminPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询管理员详情
     * @param id
     * @return
     */
    public AdminVO getById(Long id) {
        Admin admin = adminMapper.selectById(id);
        // 假设 regionIds 是一个逗号分隔的字符串
        String regionIds = admin.getRegionIds();
        // 将 regionIds 字符串解析为 Long 数组
        List<Long> regionIdList = Arrays.stream(regionIds.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());

        // 通过 regionIdList 查询区域名称列表
        List<Region> regions = regionMapper.selectByIds(regionIdList);

        // 将区域名称提取出来，存储到 AdminDetailVO 中
        List<String> regionNames = regions.stream()
                .map(Region::getName)
                .collect(Collectors.toList());

        AdminVO adminDetailVO = new AdminVO();
        BeanUtils.copyProperties(admin, adminDetailVO);
        adminDetailVO.setRegionNames(regionNames);
        return adminDetailVO;

    }


    /**
     * 更新管理员信息
     * @param admin
     */
    @Override
    public void update(Admin admin) {
        Admin admin1 = adminMapper.selectById(admin.getId());
        if(admin1.getType() == Admin.REGION_ADMIN && admin.getType() == Admin.PLATFORM_ADMIN){
            admin.setRegionIds("0");
        }
        adminMapper.update(admin);
    }

    /**
     * 管理员启用/禁用
     * @param status
     * @param id
     */
    public void updateStatus(Integer status, Long id) {
        Admin admin =Admin.builder()
                .id(id)
                .status(status)
                .build();
        adminMapper.update(admin);
    }
}
